import 'dart:io';

import 'package:common/common.dart';
import 'package:dio/dio.dart';
import 'package:path/path.dart' as paths; // 导入path库
// import 'package:path/path.dart'; // 导入path库
import 'package:path_provider/path_provider.dart';

class AudioDownLoad {
  factory AudioDownLoad() => _getInstance();
  static AudioDownLoad get instance => _getInstance();
  static AudioDownLoad? _instance;
  static AudioDownLoad _getInstance() {
    _instance ??= AudioDownLoad._internal();
    return _instance!;
  }

  //初始化...
  AudioDownLoad._internal() {
    //初始化其他操作...
    logs("AudioDownLoad init");
  }

  static void getFile({
    String? filePath,
    Function? onProgress,
    Function? complete,
    Function? onNetComplete,
    Function? onError,
  }) async {
    if (filePath != null) {
      String? docPath;
      if (Platform.isAndroid) {
        docPath = "/storage/emulated/0/Download/";
        // Directory dir = Directory(docPath);
        // try {
        //   dir.listSync();
        // } catch (e) {
        // 一些系统没有权限
        // docPath = (await getExternalStorageDirectory())?.path;
        docPath = (await getApplicationDocumentsDirectory()).path;
        docPath = '$docPath/';
        // }
      } else {
        docPath = (await getTemporaryDirectory()).path;
        docPath = docPath.replaceFirst("Library/Caches", "Documents/");
      }
      String fileName = paths.basename(filePath); // 使用basename函数获取文件名

      // String loadFilePath = '$docPath$fileName';

      // 下载存储路径
      String loadFilePath = '$docPath$fileName';

      // 删除文件
      // _deleteFile(path: loadFilePath);

      // 文件保存路径
      String okFilePrefix = "ok_ok_";
      String okFilePath = '$docPath$okFilePrefix$fileName';

      File file = File(okFilePath);
      if (await file.exists()) {
        logs('audio_downLoad =  文件已经存在');
        if (complete != null) {
          complete(okFilePath);
        }
        return;
      } else {
        if (onNetComplete != null) {
          onNetComplete(filePath);
        }
      }

      try {
        Response res = await Dio().download(filePath, loadFilePath, onReceiveProgress: (int received, int total) {
          if (total != -1) {
            String progress = (received / total * 100).toStringAsFixed(0);
            // 下载进度
            logs('audio_downLoad = progress = $progress');
            if (onProgress != null) {
              onProgress(progress);
            }
          }
        });
        if (res.statusCode == 200) {
          // if (complete != null) {
          //   complete(loadFilePath);
          // }

          // 下载完成的文件重新命名,防止出现未下载到完整的文件
          File file1 = File(loadFilePath);
          String newLoadFilePath = '$docPath$okFilePrefix$fileName';
          File file2 = file1.renameSync(newLoadFilePath);
          // 检查文件是否重命名成功
          if (file2.existsSync()) {
            logs('audio_downLoad = 文件重命名成功');
            if (complete != null) {
              complete(newLoadFilePath);
            }
          } else {
            logs('audio_downLoad = 文件重命名失败');
          }
        } else {
          if (onError != null) {
            onError();
          }
        }
        logs('audio_downLoad = $res');
      } catch (e) {
        // Toast.showCenter('语音文件错误,请稍候重试');
        if (onError != null) {
          onError();
        }
        logs('audio_downLoad =  error = ${e.toString()}');
      }
    }
  }

  // static void _deleteFile({required String path}) {
  //   try {
  //     File file = File(path);
  //     if (file.existsSync()) {
  //       file.delete();
  //     } else {}
  //   } catch (e) {
  //     logs(e.toString());
  //   }
  // }
}
